<template>
  <d2-container>
    <el-form :model="FormSearch" status-icon label-width="100px" class="demo-ruleForm">
      <el-row :gutter="24">
        <el-col :span="5">
          <el-form-item label="条件查找" prop="sortName">
            <el-input
              type="text"
              v-model="FormSearch.sortName"
              placeholder="请输入姓名"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-select v-model="typeId" placeholder="请选择员工分类">
            <el-option
              v-for="item in type"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="searchClick()">查询</el-button>
          <el-button @click="resetForm()">重置</el-button>
        </el-col>
        <el-col :span="3">
            <el-upload
              class="upload-demo"
              :data="uploadData"
              :action="uploadPl"
              :before-upload="beforeChange"
              :on-success="handleChange"
              :show-file-list="false"
            >
              <el-button type="primary">批量导入员工信息</el-button>
            </el-upload>
            </el-col>
            <el-col :span="4">
            <el-button type="primary" @click="daochu">导出</el-button>
            <el-button type="primary" @click="xz">下载导入格式</el-button>
            </el-col>
      </el-row>
    </el-form>
    <!-- 数据表格 -->
    <d2-crud
      ref="d2Crud"
      edit-title="编辑"
      add-title="添加员工"
      :columns="columns"
      :rowHandle="rowHandle"
      :edit-template="editTemplate"
      :data="data"
      :add-template="addTemplate"
      :add-rules="addRules"
      :form-options="formOptions"
      :pagination="page"
      :loading="loading"
      @dialog-open="handleDialogOpen"
      @row-edit="handleRowEdit"
      @row-add="handleRowAdd"
      @custom-emit-2="delGood"
      @dialog-cancel="handleDialogCancel"
      @pagination-current-change="paginationCurrentChange"
    >
    <el-button slot="header" style="margin-bottom: 5px;" @click="addRow">添加员工</el-button>
    </d2-crud>
  </d2-container>
</template>

<script>
import {
  getStaff,
  getGoodType,
  deleteStaff,
  addStaff,
  exportStaff,
  updateStaff
  } from "@/api/goods/index";
// 查看图片组件
import good_img from "@/components/xtnComponents/Good_img";
// 查看和上传图片组件
import upload_img from "@/components/xtnComponents/UploadImg";

export default {
  data() {
    return {
      uploadPl: process.env.VUE_APP_API + "/staff/impStaff",
      loading: false,
      uploadData: {},
      // 搜索数据
      FormSearch: {
        sortName: ""
      },
      typeId: '',
      type: [],
      // 字段名称
      columns: [
        {
          title: "姓名",
          key: "name",
          align: "center"
        },
        {
          title: "手机号",
          key: "phone",
          align: "center"
        },
        {
          title: "补贴金额",
          key: "money",
          align: "center"
        },
        {
          title: "优惠结束时间",
          key: "end_time",
          align: "center"
        },
        {
          title: "科室地址",
          key: "department",
          align: "center"
        },
      ],
      // 列表数据
      data: [],
      // 操作列数据
      rowHandle: {
        align: "center",
        width: 200,
        custom: [
          /* {
            text: "重置密码",
            type: "primary",
            size: "mini",
            emit: "custom-emit-1"
          }, */
          {
            text: "删除",
            type: "danger",
            size: "mini",
            emit: "custom-emit-2"
          },
        ],
        edit: {
          icon: "el-icon-edit",
          text: "编辑",
          size: "small"
        }
      },
      addTemplate: {
        name: {
          title: "姓名",
          value: ""
        },
        phone: {
          title: "手机号",
          value: ""
        },
        passWord: {
          title: "密码",
          value: ""
        },
        typeId: {
          title: "员工分类",
          value: "",
          component: {
            name: 'el-select',
            options: [],
          }
        },
        money: {
          title: "补贴金额",
          value: ""
        },
        endTime: {
          title: "优惠结束时间",
          value: "",
          component: {
            name: 'el-date-picker',
            valueFormat: 'yyyy/MM/dd',
          }
        },
        department: {
          title: "科室地址",
          value: "",
          component: {
            name: 'el-select',
            options: [],
          }
        },
      },
      addRules: {
        name: [ { required: true, message: '请输入姓名', trigger: 'blur' } ],
        phone: [ { required: true, trigger: 'blur',
        validator: (rule, value) => {
          return new Promise((resolve, reject) => {
            if (value === '') {
              reject("请输入手机号");  // reject with error message
            } else if (!(/^1[1234567890]\d{9}$/.test(value))) {
              reject("请输入正确的手机号");
            } else {
              resolve()
            }
          });
        } } ],
        passWord: [ { required: true, message: '请输入密码', trigger: 'blur' } ],
        money: [ { required: true, message: '请输入补贴金额', trigger: 'blur' } ],
        typeId: [ { required: true, message: '请选择员工分类', trigger: 'blur' } ],
        department: [ { required: true, message: '请输入科室地址', trigger: 'blur' } ],
      },
      editTemplate: {
        name: {
          title: "姓名",
          value: ""
        },
        phone: {
          title: "手机号",
          value: ""
        },
        pass_word: {
          title: "密码",
          value: ""
        },
        money: {
          title: "补贴金额",
          value: ""
        },
        end_time: {
          title: "优惠结束时间",
          value: "",
          component: {
            name: 'el-date-picker',
            valueFormat: 'yyyy/MM/dd',
          }
        },
        department: {
          title: "科室地址",
          value: "",
          component: {
            name: 'el-select',
            options: [],
          }
        },
      },
      formOptions: {
        labelWidth: "80px",
        labelPosition: "left",
        saveLoading: false
      },
      // 分页数据
      page: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      }
    };
  },
  created() {
    let params = {
      page: this.page.pageIndex,
      limit: this.page.pageSize
    };
    this.init(params);
  },
  mounted() {
    let params = {
      page: 1,
      limit: 9999999
    };
    params.type = 2
    getGoodType(params)
      .then(res => {
        if (res.success) {
          let zopt = []
            res.rows.map(item => {
              let opt = {
                value: item.id,
                label: item.name
              }
              zopt.push(opt)
            })
            this.type = zopt
            this.addTemplate.department.component.options = zopt
            this.type = zopt
        }
      })
      .catch(err => {
        this.$message.error(err);
      });
      params.type = 1
      getGoodType(params)
        .then(res => {
          if (res.success) {
            let zopt = []
              res.rows.map(item => {
                let opt = {
                  value: item.name,
                  label: item.name
                }
                zopt.push(opt)
              })
              this.addTemplate.department.component.options = zopt
              this.editTemplate.department.component.options = zopt
          }
        })
        .catch(err => {
          this.$message.error(err);
        });
  },
  methods: {
    // 初始化身体数据列表
    init(params) {
      this.loading = true
      getStaff(params)
        .then(res => {
          if (res.success) {
            res.rows.map(item => {
              if (item.end_time) {
                item.end_time = new Date(item.end_time).toLocaleDateString()
              }
            })
            this.data = res.rows || [];
            this.page.total = res.total;
          }
          this.loading = false
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err);
        });
    },

    // 分页数改变，调用
    paginationCurrentChange(pageIndex) {
      let params = {
        limit: this.page.pageSize,
        name: this.FormSearch.sortName,
      };
      params.page = this.page.pageIndex = pageIndex;
      this.init(params);
    },

    // 普通的新增
    addRow() {
      this.$refs.d2Crud.showDialog({
        mode: "add"
      });
    },

    // 新增成功
    handleRowAdd(row, done) {
      this.formOptions.saveLoading = true;
      let params = row;
      console.log(params)
      addStaff(params)
        .then(res => {
          console.log(res);
          if (res.success) {
            this.$message({
              message: "添加成功",
              type: "success"
            });
          }
          sessionStorage.imgUrl = ''

          // done可以传入一个对象来修改提交的某个字段
          done();
          // 保存按钮的loading状态
          this.formOptions.saveLoading = false;
          // 重新加载列表
          let params = {
            page: this.page.pageIndex,
            limit: this.page.pageSize,
          };
          this.init(params);
        })
        .catch(err => {
          this.$message.error(err);
        });
    },

    // 上传之前
    beforeChange(file) {
      if (this.typeId == '') {
        this.$message({
          message: "请选择员工分类",
          type: "info"
        });
        return false
      }
      this.uploadData = {
        typeId: this.typeId
      }
    },

    // 上传文件成功或失败的回调
    handleChange(response, file, fileList) {
      console.log(response, file, fileList);
      if (response.success) {
        this.$message({
          message: "上传成功,请刷新后查看",
          type: "success"
        });
      }
      let params = {
        page: 1,
        limit: 10,
      };
      this.init(params);
    },

    // 点击编辑时 mode 为编辑或者添加，row为点击这一行数据
    handleDialogOpen({ mode, row }) {
    },

    // 导出
    daochu() {
      let params = {
        typeId: this.typeId
      }
      window.location.href = process.env.VUE_APP_API + "/staff/exportStaff?typeId=" + this.typeId + '&name=' + this.FormSearch.sortName
    },

    // 下载导入格式
    xz() {
      // window.open(process.env.VUE_APP_API + '/pc/%E5%91%98%E5%B7%A5%E7%99%BD%E5%90%8D%E5%8D%95%E5%AF%BC%E5%85%A5%E6%A0%BC%E5%BC%8F.xlsx');
      window.location.href =  process.env.VUE_APP_API + '/pc/%E5%91%98%E5%B7%A5%E7%99%BD%E5%90%8D%E5%8D%95%E5%AF%BC%E5%85%A5%E6%A0%BC%E5%BC%8F.xlsx'
    },

    // 编辑提交
    handleRowEdit({ index, row }, done) {
      // 保存按钮的loading状态
      this.formOptions.saveLoading = true;
      let params = {};
      params.id = row.id;
      params.name = row.name;
      params.phone = row.phone;
      params.passWord = row.pass_word;
      params.money = row.money;
      params.department = row.department;
      params.endTime = row.end_time;
      updateStaff(params)
        .then(res => {
          if (res.success) {
            this.$message({
              message: "编辑成功",
              type: "success"
            });
          }
          sessionStorage.imgUrl = ''
          
          // done可以传入一个对象来修改提交的某个字段
          done();
          // 保存按钮的loading状态
          this.formOptions.saveLoading = false;
          // 重新加载列表
          let params = {
            page: this.page.pageIndex,
            limit: this.page.pageSize
          };
          this.init(params);
        })
        .catch(err => {
          this.$message.error(err);
        });
    },

    // 删除商品
    delGood({ index, row }) {
      let params = {
        id: row.id,
      }
      this.$confirm(`此操作将删除此信息, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteStaff(params)
            .then(res => {
              if (res.success) {
                this.$message({
                  message: "删除成功",
                  type: "success"
                });
                // 重新加载列表
                let params = {
                  page: this.page.pageIndex,
                  limit: this.page.pageSize,
                };
                this.init(params);
              }
            })
            .catch(err => {
              this.$message.error(err);
            });
        })
        .catch(err => {});
    },

    // 条件查询搜索
    searchClick() {
      let params = {
        page: 1,
        limit: 10
      };
      params.name = this.FormSearch.sortName;
      this.init(params);
    },

    // 重置查询
    resetForm() {
      this.FormSearch.sortName = "";
      let params = {
        page: 1,
        limit: 10
      };
      this.init(params);
    },

    // 取消编辑和添加
    handleDialogCancel(done) {
      /* this.$message({
        message: "取消操作",
        type: "warning"
      }); */
      done();
    }
  }
};
</script>
<style lang="scss" scoped>
</style>
